load('../src/ph/ph.js');

ph.bootstrap('settings.js');
ph.keepRunning();

dojo.require('ph.bluetooth');
dojo.require('flickr.Flickr');
dojo.require('jetty.Server');

SCAN_INTERVAL    = 10000;
RELOAD_INTERVAL  = 10000;

flickrApi = new flickr.Flickr(FLICKR_API);
scanner = ph.bluetooth.scanner();
server = new jetty.Server(8080, jettyResources);

photosByUser = {};

dojo.connect(scanner, 'onAppear', function(evt) {
  print('Found ' + evt.name);
  
  spawn(function() {
    try {
      var username = flickr.Flickr.findUsernameByUrlName(evt.name) || evt.name;
      var user     = flickrApi.people.findByUsername({username: username});
      var photos   = flickrApi.people.getPublicPhotos({user_id: user.user.nsid, per_page: 5});
      photosByUser[evt.name] = photos.photos.photo;
    } catch(e) {
      print(e);
    }
  });
});

dojo.connect(scanner, 'onDisappear', function(evt) {
  delete photosByUser[evt.name];
});

server.register('/', function(request, response) {
  var html = '<script>setTimeout(function(){window.location.reload()}, ' + RELOAD_INTERVAL + ')</script>';
  for (var name in photosByUser) {
    if (!photosByUser.hasOwnProperty(name)) continue;
    
    var photos = photosByUser[name];
    for (var i = 0; i < photos.length; i++) {
      html += '<img src="' + flickr.Flickr.toPhotoUrl(photos[i]) + '">';
    }
  }
  
  response.contentType = 'text/html';
  response.body = html;
});

scanner.run(SCAN_INTERVAL);
server.start();